import React, { memo ,useState} from 'react'
import { useSelector, shallowEqual ,useDispatch} from "react-redux";
import {
  getSizeImage,
  formatMinuteSecond
} from "@/utils/format-utils.js"
import {addPlayListSong,getCurrentSongAction,changeIsShowMessage} from 'pages/player/store/actionCreators'
import {
  RankingListWrapper
} from './style';
export default memo(function HNRankingList() {

  const [isHover,setIsHover] = useState(false);
  const [currentIndex , setCurrnetIndex] = useState(-1);
  const dispatch = useDispatch();
  const state = useSelector(state => ({
    playlistDetail : state.getIn(["ranking", "playlistDetail"]),
  }), shallowEqual);

  const tracks = ((state.playlistDetail) && (state.playlistDetail.tracks )) || [];

  const mouseEnterChange = (item,index) =>{
    if(!(isHover && currentIndex === index)){
      return <td >{formatMinuteSecond(item.dt)}</td>
    }else{
      return <td className="add sprite_icon2" onClick={e=>addSong(item.id)}></td>
    }  
  }

  const mouseEnter = index => {
    setIsHover(true);
    setCurrnetIndex(index);
  }

  const addSong = id => {
    dispatch(addPlayListSong(id));
    setTimeout(()=>{
      dispatch(changeIsShowMessage(false));
    },2000)
  }

  const play = id => {
   dispatch( getCurrentSongAction(id));
  }

  return (
    <RankingListWrapper>
    <div className="play-list">
      <table>
        <thead>
          <tr className="header">
            <th className="ranking"></th>
            <th className="title">标题</th>
            <th className="duration">时长</th>
            <th className="singer">歌手</th>
          </tr>
        </thead>
        <tbody>
          {
            tracks.map((item, index) => {
              return (
                <tr className="" key={item.id} onMouseEnter={e=>{mouseEnter(index)}}
                                               onMouseLeave={e=>{setIsHover(false)}}>
                  <td className>
                    <div className="rank-num">
                      <span className="num">{index + 1}</span>
                      <span className="new sprite_icon2"></span>
                    </div>
                  </td>
                  <td>
                    <div className="song-name">
                      {
                        index <3 && <img src={getSizeImage(item.al.picUrl, 50)} alt="" />
                      }
                      <span className="play sprite_table" onClick={e=>{play(item.id)}}></span>
                      <span className="name">{item.name}</span>
                    </div>
                  </td>
                  {mouseEnterChange(item,index)}
                  <td>{item.ar[0].name}</td>
                </tr>
              )
            })
          }
        </tbody>
      </table>
    </div>
  </RankingListWrapper>
  )
})
